//
//  SLPreferencesSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/23.
//

#import "SLBridgeLockListVC.h"
#import "SLPreferencesSetCell.h"
#import "SLAddLockScanVC.h"
#import "SLBridgeLockCell.h"

static  NSString *const kCellId1 = @"SLPreferencesSetCell";
static  NSString *const kCellId2 = @"SLBridgeLockCell";
@interface SLBridgeLockListVC ()<UITableViewDelegate,UITableViewDataSource>{
    NSArray *_deviceInfo;
    BOOL _isEditing;
    UIButton *_deleteBtn;
}
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;
@end

@implementation SLBridgeLockListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
    [self loadData];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Connected devices");
    _deleteBtn = [self addNavigationItemWithImageNames:@[@"icon_delete"] isLeft:NO target:self action:@selector(deleteAction:) tags:@[@"1000"]][0];
    [_deleteBtn setImage:[UIImage imageNamed:@"icon_reset"] forState:UIControlStateSelected];
    [self confiDatas];
    [self.view addSubview:self.tableView];
}

-(void)deleteAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    _isEditing = sender.isSelected;
    [_tableView reloadData];
}

-(void)deleteBridgeLock:(SLLockModel *)lockModel{
    [SLTipAlertView showWith:kLocalString(@"Please note") content1:kLocalString(@"Are you sure to delete this lock?") content2:@"" doneBtn:kLocalString(@"Delete") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
        if (index == 0) {
            return;
        }
        [ZCTool showLoadingOnKeyWindow];
        //断开并解绑设备
        NSDictionary *params = @{@"deviceNo":kCurClickDevice.deviceNo,
                                 @"conId":lockModel.conId,
                                 @"timeout":@(60)};
        [ZCTool showLoadingOnKeyWindow];
        [ZKHttpManager postWithPath:@"/msl_user/disconDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                kShowToast(message);
                return;
            }
            [self loadData];
            kNotifyRefreshDevcieList;
        }];
    }];
}

-(void)loadData{
    [ZCTool showLoadingOnKeyWindow];
    NSString *url = [NSString stringWithFormat:@"/msl_user/terminalInfo/%@",kCurClickDevice.deviceNo];
    [ZKHttpManager getWithPath:url params:@{} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        //更新页面
        self->_deviceInfo = result[@"result"];
        [self refreshSubViews];
    }];
}

-(void)confiDatas{
    [self.dataArray removeAllObjects];
    
    NSArray *sectionTitle2 = @[kLocalString(@"Add new device")];
    NSArray *sectionContent2 = @[@""];
    NSMutableArray *section1 = [NSMutableArray new];
    
    [_deviceInfo enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SLLockModel *model = [SLLockModel new];
        model.deviceNo = obj[@"license"];
        model.deviceName = obj[@"deviceName"];
        model.deviceId = obj[@"deviceId"];
        model.onlineStatus = kSTRING(obj[@"onlineStatus"]);
        model.networkMode = obj[@"networkMode"];
        model.conId = obj[@"conId"];
        [section1 addObject:model];
    }];
    
    NSMutableArray *section2 = [NSMutableArray new];
    [sectionTitle2 enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *info = [NSMutableDictionary new];
        NSString *content = sectionContent2[idx];
        [info setObject:title forKey:@"title"];
        [info setObject:content forKey:@"content"];
        [info setObject:@"1" forKey:@"type"];
        [section2 addObject:info];
    }];
    
    [_dataArray addObject:section1];
    [_dataArray addObject:section2];
}

-(void)refreshSubViews{
    [self confiDatas];
    [_tableView reloadData];
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionArr = _dataArray[section];
    return sectionArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLPreferencesSetCell *cell1 = [tableView dequeueReusableCellWithIdentifier:kCellId1];
    SLBridgeLockCell *cell2 = [tableView dequeueReusableCellWithIdentifier:kCellId2];
    UITableViewCell *cell = nil;
    cell1.selectionStyle = UITableViewCellSelectionStyleNone;
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    id info = _dataArray[indexPath.section][indexPath.row];
    NSArray *section = _dataArray[indexPath.section];
    if ([info isKindOfClass:[SLLockModel class]]) {
        SLLockModel *model = info;
        cell2.lockModel = model;
        cell2.isEditing = _isEditing;
        cell2.line.hidden = indexPath.row == section.count-1;
        kWeakSelf(self);
        [cell2 setDeleteBlock:^(SLLockModel * _Nonnull lockModel) {
            [weakself deleteBridgeLock:lockModel];
        }];
        cell = cell2;
    }else{
        cell1.titleLbl.text = info[@"title"];
        cell1.contentLbl.text = info[@"content"];
        cell1.line.hidden = indexPath.row == section.count-1;
        cell1.changeBtn.hidden = YES;
        cell1.list.hidden = NO;
        cell = cell1;
    }
    
    [cell.contentView setRoundedCorners:0 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    if (indexPath.row == section.count-1) {
        if (section.count == 1) {
            [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
        }else{
            [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
        }
    }else if (indexPath.row == 0){
        [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerTopLeft | UIRectCornerTopRight frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    }
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 20);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *info = _dataArray[indexPath.section][indexPath.row];
    NSString *title = info[@"title"];
    if ([title isEqualToString:kLocalString(@"Add new device")]) {
        SLAddLockScanVC *vc = [[SLAddLockScanVC alloc] init];
        vc.type = 1;
        vc.isBridgeAddLock = YES;
        vc.bridgeListVc = self;
        kWeakSelf(self);
        [vc setAddLockBlock:^{
            [weakself loadData];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, SafeAreaTopHeight,kScreenWidth-40,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId1 bundle:nil] forCellReuseIdentifier:kCellId1];
        [_tableView registerNib:[UINib nibWithNibName:kCellId2 bundle:nil] forCellReuseIdentifier:kCellId2];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

@end
